import URL from "url";
import protocolConfig from "../var/protocolConfigFunc";
import { readFile} from "./fileFunc";
import http from "http";
import https from "https";

export namespace HTTPFunc {
    export type TReqMode = "POST" | "GET";
}

export function isValidURL(url: string) {
    const urlObj = URL.parse(url);
    if (urlObj.protocol === "akaba:" || urlObj.protocol === "http:" || urlObj.protocol === "https:") {
        if (urlObj.pathname) {
            return true;
        }
    }
    return false;
}

export function requestText(
    url: string,
    encoding: string = "utf8",
    method: HTTPFunc.TReqMode = "GET",
    otherOptions: http.RequestOptions | https.RequestOptions = {}
) {
    const urlObject = URL.parse(url);
    if (!urlObject.pathname) {
        return Promise.reject(new Error("path name is null"));
    }
    switch (urlObject.protocol) {
        case "akaba:":
            return requestTextInProtocolAkaba(url);
        case "http:":
            return requestTextInProtocol(url, false, encoding, method, otherOptions);
        case "https:":
            return requestTextInProtocol(url, true, encoding, method, otherOptions);
    }
    return Promise.reject(new Error("wrong protocol "));
}

export function requestTextInProtocolAkaba(url: string) {
    const filePath = protocolConfig.akaba.getPath(url);
    return readFile(filePath);
}

export function requestTextInProtocol(
    url: string,
    isHttps: boolean = false,
    encoding: string = "utf8",
    method: HTTPFunc.TReqMode = "GET",
    otherOptions: http.RequestOptions | https.RequestOptions = {}
) {
    return new Promise<string>((resolve, reject) => {
        let netProtocol: typeof http | typeof https = http;
        if (isHttps) {
            netProtocol = https;
        }
        const req = netProtocol.request(url, Object.assign({
            method,
        }, otherOptions), (res) => {
            let data: string = "";
            res.setEncoding(encoding as any);
            res.on("data", (chunk) => {
                data += chunk;
            });
            res.on("end", () => {
                resolve(data);
            });
            res.on("error", (err) => {
                reject(err);
            });
        });
        req.on("error", (err) => {
            reject(err);
        });
        req.end();
    });
}

export function parseURL(url: string) {
    return URL.parse(url);
}
